import json

import pymysql


class DB:
    def set(self, key, value):
        self.d[key] = value
        self.save()

    def get(self, key):
        return self.d[key]

    def keys(self):
        return [{'key': key, 'value': self.d[key]} for key in self.d]


class JsonDB(DB):

    def __init__(self):
        self.path = 'note.json'
        self.d = {}

        self.load()

    def load(self):
        with open(self.path, encoding='utf8') as fp:
            self.d = json.load(fp)

    def save(self):
        with open(self.path, 'w', encoding='utf8') as fp:
            json.dump(self.d, fp)


class SqlDB(DB):

    def __init__(self):
        self.database = 'note'
        self.mysql = None
        self.init_mysql()

        self.d = {}

        self.load()

    def init_mysql(self):
        self.mysql = pymysql.connect(host='114.115.136.139', user='root', passwd='root',
                                     database=self.database,
                                     autocommit=True)

    def load(self):
        cursor = self.mysql.cursor()
        cursor.execute('select * from line')

        for line in cursor.fetchall():
            self.d[line[0]] = {'value': line[1], 'type': line[2]}

        cursor.close()
        self.mysql.close()
        self.init_mysql()

    def set(self, key, value):

        value2 = value['value'].replace('\\', '\\\\').replace('\"', '\\\"')
        cursor = self.mysql.cursor()
        if key in self.d:
            sql = f"""
    update line set v="{value2}",type="{value['type']}" where k="{key}";
    """
        else:
            sql = f"""
    insert into line (k, v, type)
    value ("{key}", "{value2}","{value['type']}");
    """
        cursor.execute(sql)
        cursor.close()
        # self.mysql.close()
        # self.init_mysql()

        self.d[key] = value


DBClass = SqlDB
